// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MBTNavigatorSDKConnection.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.Forge.Plugins
{
    #region Using Directives

    using MBTCOMLib;

    using MBTQUOTELib;

    using Org.OpenTrader.Framework.Enums;

    #endregion

    /// <summary>
    /// The mbt navigator sdk Connection.
    /// </summary>
    public class MBTNavigatorSDKConnection : Connection
    {
        private static readonly Identity Identity = Identity.Create(System.Reflection.MethodBase.GetCurrentMethod());

        #region Constants and Fields

        /// <summary>
        /// The SDK accountId.
        /// </summary>
        private readonly int accountId;

        /// <summary>
        /// The user password.
        /// </summary>
        private readonly string password;

        /// <summary>
        /// The user to log in.
        /// </summary>
        private readonly string user;

        /// <summary>
        /// The connected state.
        /// </summary>
        private bool connected;

        /// <summary>
        /// The connecting state.
        /// </summary>
        private bool connecting;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="MBTNavigatorSDKConnection"/> class.
        /// </summary>
        /// <param name="accountId">
        /// The accountId.
        /// </param>
        /// <param name="user">
        /// The user to log in.
        /// </param>
        /// <param name="password">
        /// The user password.
        /// </param>
        /// <param name="layer">
        /// The layer owning this Connection.
        /// </param>
        public MBTNavigatorSDKConnection(int accountId, string user, string password, MBTNavigatorSDKFeedPlugin layer)
            : base(layer)
        {
            this.accountId = accountId;
            this.user = user;
            this.password = password;
        }

        /// <summary>
        /// Finalizes an instance of the <see cref="MBTNavigatorSDKConnection"/> class. 
        /// </summary>
        ~MBTNavigatorSDKConnection()
        {
            this.ReleaseCOM();
        }

        #endregion

        #region Properties

        /// <summary>
        /// The current status of the Connection
        /// </summary>
        public override EConnectionStatus ConnectionStatus
        {
            get
            {
                if (this.connecting)
                {
                    return EConnectionStatus.Connecting;
                }

                if (this.connected)
                {
                    return EConnectionStatus.Connected;
                }

                return EConnectionStatus.Disconnected;
            }
        }

        /// <summary>
        /// Gets MbtComMgr.
        /// </summary>
        public MbtComMgr MbtComMgr { get; private set; }

        /// <summary>
        /// Gets MbtQuotes.
        /// </summary>
        public MbtQuotes MbtQuotes { get; private set; }

        #endregion

        #region Public Methods

        /// <summary>
        /// The connect.
        /// </summary>
        public override Status Connect()
        {
            // Already connected
            if (this.connecting)
            {
                return Status.Failure(Identity, "Already connecting");
            }

            // We're connecting
            this.RaiseConnectingEvent();

            // Do it
            this.ConnectImpl();

            return Status.Success(Identity);
        }

        /// <summary>
        /// The disconnect.
        /// </summary>
        public override Status Disconnect()
        {
            // Not connected
            if (this.ConnectionStatus != EConnectionStatus.Connected)
            {
                return Status.Failure(Identity, "Not connected");
            }

            // We're disconnecting
            this.RaiseConnectingEvent();

            // Do it
            this.DisconnectImpl();

            return Status.Success(Identity);
        }

        /// <summary>
        /// The to string.
        /// </summary>
        /// <returns>
        /// An URL like string representation of the Connection string
        /// </returns>
        public override string ToString()
        {
            return string.Format("User={0} AccountID={1}", this.user, this.accountId);
        }

        #endregion

        #region Methods

        /// <summary>
        /// The connect impl.
        /// </summary>
        private void ConnectImpl()
        {
            // Currently connecting
            this.connecting = true;

            // Create
            this.MbtComMgr = new MbtComMgr();
            this.MbtQuotes = this.MbtComMgr.Quotes;

            // Silence all this bad blurb :>
            this.MbtComMgr.EnableSplash(false);
            this.MbtComMgr.SilentMode = true;

            // MbtComMgr.OrderClient.SilentMode = true;

            // Subscribe to events
            this.MbtComMgr.OnCriticalShutdown += this.MbtComMgrOnCriticalShutdown;
            this.MbtComMgr.OnLogonSucceed += this.MbtComMgrOnLogonSucceed;
            this.MbtComMgr.OnLogonDeny += this.MbtComMgrOnLogonDeny;

            // Login
            var b = this.MbtComMgr.DoLogin(this.accountId, this.user, this.password, string.Empty);

            // Not connecting currently
            this.connecting = false;
        }

        /// <summary>
        /// The disconnect impl.
        /// </summary>
        private void DisconnectImpl()
        {
            // Reset 
            this.connected = false;
            this.connecting = false;

            // Unsubscribe
            this.MbtComMgr.OnCriticalShutdown -= this.MbtComMgrOnCriticalShutdown;
            this.MbtComMgr.OnLogonSucceed -= this.MbtComMgrOnLogonSucceed;
            this.MbtComMgr.OnLogonDeny -= this.MbtComMgrOnLogonDeny;

            // Release
            this.ReleaseCOM();

            // We're out
            this.RaiseDisconnectedEvent();
        }

        /// <summary>
        /// The mbt com mgr_ on critical shutdown.
        /// </summary>
        private void MbtComMgrOnCriticalShutdown()
        {
            this.DisconnectImpl();
        }

        /// <summary>
        /// The mbt com mgr_ on logon deny.
        /// </summary>
        /// <param name="bstrReason">
        /// The bstr reason.
        /// </param>
        private void MbtComMgrOnLogonDeny(string bstrReason)
        {
            this.DisconnectImpl();
        }

        /// <summary>
        /// The mbt com mgr_ on logon succeed.
        /// </summary>
        private void MbtComMgrOnLogonSucceed()
        {
            this.connecting = false;
            this.connected = true;

            // We're in
            this.RaiseConnectedEvent();
        }

        /// <summary>
        /// Force the Interop layer to release Com objects, else re-Connection is impossible
        /// </summary>
        private void ReleaseCOM()
        {
            try
            {
                if (this.MbtQuotes != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(this.MbtQuotes);
                }

                if (this.MbtComMgr != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(this.MbtComMgr);
                }

                this.MbtQuotes = null;
                this.MbtComMgr = null;
            }
            catch
            {
            }
        }

        #endregion
    }
}